package com.app;

import java.io.File;
import java.util.HashMap;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Environment;

import com.app.util.Utils_Log;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;


public class ApplicationCustom extends Application {

	public static ApplicationCustom mInstance;
	private static String TAG = ApplicationCustom.class.getSimpleName();
	private static final String CACHE_DIR_NAME = "cache";
	
	
	 
	public static boolean isTestMode = false;
	
	
	
	// 百度定位
	//public mylocation loc;


	/**
	 * 获取Application
	 * 
	 * @Title: getInstance
	 * @Description: 获取Application
	 * @return CustomApplication 实例
	 * @throws
	 */
	public static ApplicationCustom getInstance() {
		return mInstance;
	}

	@Override
	public void onCreate() {
		Utils_Log.i(TAG, "onCreate");
		super.onCreate();
		Thread.setDefaultUncaughtExceptionHandler(AppException
				.getAppExceptionHandler()); // 控制捕获异常

		mInstance = this;

		init();// 初始化配置

	}

	/**
	 * 初始化配置APP基本信息
	 * 
	 * @Title: init
	 * @Description: 初始化配置APP基本信息
	 * @return void 返回类型
	 * @throws
	 */
	public void init() {

		
		Config.init(getApplicationContext());
		
		
		// 初始化内核
		//String CacheDir = getCacheDir().toString();
		//CoreConfig.init( CacheDir );
		com.app.G.init(this, new HashMap<String, Object>());
		
		
		initLoc();
		initSavePath();
		initKey();

		initString();
		initData();// 初始化share数据

		 // 初始化购物车数据
		initImageLoader(getApplicationContext());// 初始化ImageLoader
		
		
	}

	private void initLoc() {

		//loc = new mylocation(getApplicationContext());
		// loc.start();
	}

	private void initSavePath() {


		// 得到包名
		Config.PACK_NAME = getApplicationContext().getPackageName();

		
		// 扩展储存是否存在
		boolean sdcardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		
		if( sdcardExist ){
			File sdCardpath = Environment.getExternalStorageDirectory();
			File dbPath = new File(sdCardpath, Config.PACK_NAME);
			String str_dir = dbPath.getPath();
			if (Config.INSIDE_PIC) // 保存在包内，这样卸载应用程序，内部的图片也会被删除; (inside话，拍照图片无法保存）
				str_dir = getApplicationContext().getCacheDir().getPath();
			File dir = new File(str_dir, "tmp/pic"); // /mnt/sdcard/***/file
			if (!dir.exists())
				dir.mkdirs();
			
			// 拍照图片保存路径
			Config.PIC_TEMP_SAVE_PATH = dir.getAbsolutePath();
		}
		else{
			File dir = new File(getCacheDir(), "tmp/pic"); // 
			if (!dir.exists())
				dir.mkdirs();
			
			// 拍照图片保存路径
			Config.PIC_TEMP_SAVE_PATH = dir.getAbsolutePath();
		}
		
		
		
		

	}

	private void initKey() {
		// 应用程序入口处调用,避免手机内存过小，杀死后台进程,造成SpeechUtility对象为null
		// 设置你申请的应用appid
//		SpeechUtility.createUtility(this, "appid=" + Config.app_id_voice);
	}

	private void initString() {

		/*
		new TIME_HIGHT() {
			public void fuc() {

				// 08-20 16:32:49.892: I/System.out(1335):
				// 加载资源===----0.001547s----1.547ms----1547.0微秒
				S.init(getApplicationContext());

			};

			@Override
			public String give_msg() {
				// TODO Auto-generated method stub
				return "加载资源===";
			}
		}.get_elapsed_time();
		*/

	}

	private void initSqlDb() {
		// TODO Auto-generated method stub
		
		//不管是xUtils.jar还是dhroid.jar所依赖的bean都需要注入的操作， xUtils操作更简便
		//DbUtils.create(this, "fuguojijin").save(entity);
	
		
		// 创建数据库文件
		
		
		
		
	}

	private void initData() {

		
		/*
		{
			HomeSearchMessage.Bean bean = new HomeSearchMessage.Bean();
			//Bean bean = new Bean();
			bean.setContent("1234");
			bean.setMd5("md55");
			//bean.setVisiable(false);
			
				
			HomeSearchMessageImpl impl = HomeSearchMessageImpl.newInstance(getApplicationContext());
			impl.CreateTable();
			impl.Save(bean);
		}
		
		
		{
			//
			CommMessage.Bean bean = new CommMessage.Bean();
			bean.setAppName("my app");
			CommMessageImpl impl_comm = CommMessageImpl.newInstance(getApplicationContext());
			impl_comm.CreateTable();
			impl_comm.Save(bean);
			
			
			// 操作
//			ContentResolver cr = this.getContentResolver(); 
//			Cursor cur = cr.query( com.provider.provider.CommMessage.CONTENT_URI, null, null, null, null);
//			System.out.println(cur);
			
		}
		*/
		
		
	}
	

		
		


	/** 初始化ImageLoader */
	public static void initImageLoader(Context context) {
		File cacheDir = StorageUtils.getOwnCacheDirectory(context, CACHE_DIR_NAME);// 获取到缓存的目录地址
		Utils_Log.d("cacheDir", cacheDir.getPath());
		
		cacheDir = new File(Config.PIC_TEMP_SAVE_PATH);
		
		// 创建配置ImageLoader(所有的选项都是可选的,只使用那些你真的想定制)，这个可以设定在APPLACATION里面，设置为全局的配置参数
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context)
				// 线程池内加载的数量
				.threadPoolSize(5).threadPriority(Thread.NORM_PRIORITY - 2)
				.memoryCache(new WeakMemoryCache())
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator()) // 将保存的时候的URI名称用MD5 加密
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.discCache(new UnlimitedDiscCache(cacheDir, new FileNameGenerator() {
					
					@Override
					public String generate(String imageUri) {
						// TODO Auto-generated method stub
						return imageUri;
					}
				}))// 自定义缓存路径
				// .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
				.writeDebugLogs() // Remove for release app
				.build();	
		
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);// 全局初始化此配置
	}

	/**
	 * 获取App安装包信息
	 * 
	 * @return
	 */
	public PackageInfo getPackageInfo() {
		PackageInfo info = null;
		try {
			info = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace(System.err);
		}
		if (info == null)
			info = new PackageInfo();
		return info;
	}

}
